package cn.yuanqiao.archive.archiveBorrow.service.impl;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantFieldsMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.archiveBorrow.domain.YqDaBorrow;
import cn.yuanqiao.archive.archiveBorrow.domain.YqdaborrowItem;
import cn.yuanqiao.archive.archiveBorrow.mapper.YqDaBorrowMapper;
import cn.yuanqiao.archive.archiveBorrow.service.IYqDaBorrowService;
import cn.yuanqiao.archive.xiaoxitongzhi.service.IYqXxtzService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;
import java.util.stream.Collectors;

/**
 * archiveBorrowService业务层处理
 *
 * @author yuanqiao
 * @date 2023-07-14
 */
@Service
public class YqDaBorrowServiceImpl implements IYqDaBorrowService
{
    @Autowired
    private YqDaBorrowMapper yqDaBorrowMapper;

    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;

    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;

    @Autowired
    private IYqXxtzService yqXxtzService;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    @Autowired
    private IYqXxtzService archiveReleaseService;
    /**
     * 查询archiveBorrow
     *
     * @param borrowId archiveBorrow主键
     * @return archiveBorrow
     */
    @Override
    public YqDaBorrow selectYqDaBorrowByBorrowId(Long borrowId)
    {
        YqDaBorrow yqDaBorrow = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(borrowId);
        Map<Long,List<TenantMdataList>> fieldMap = new HashMap<>();
        List<YqdaborrowItem> yqdaborrowItemList = yqDaBorrow.getYqdaborrowItemList();
        String thisFields = "";
        for (YqdaborrowItem item : yqdaborrowItemList) {
            Long categoryId = item.getCategoryId();
            String subTableName = item.getSubTableName();
            List<TenantMdataList> tenantMdataListCategory = null;
            if (fieldMap.get(categoryId)==null){
                tenantMdataListCategory = tenantMdataListMapper.selectTenantMdataListListByCategoryId(new TenantMdataList(), categoryId, SecurityUtils.getTenantCode() + "_CATEGORY");
                fieldMap.put(categoryId,tenantMdataListCategory);
            }else {
                tenantMdataListCategory = fieldMap.get(categoryId);
            }
            Set<String> yqdaFields = new HashSet<>();
            Set<String> yqfolderFields = new HashSet<>();
            Set<String> yqItmeFields = new HashSet<>();

            for (TenantMdataList itemCategory : tenantMdataListCategory) {
                if (Integer.valueOf(0).equals(itemCategory.getType())) {
                    yqdaFields.add(itemCategory.getFieldName());
                } else if (Integer.valueOf(1).equals(itemCategory.getType())) {
                    yqfolderFields.add(itemCategory.getFieldName());
                }else if (Integer.valueOf(3).equals(itemCategory.getType())){
                    yqItmeFields.add(itemCategory.getFieldName());
                }
            }
            String archiveId = item.getDaId();
            if ("f".equals(item.getFeedBack())){
                thisFields = StringUtils.join(yqdaFields,",")+",";
            }else if ("v".equals(item.getFeedBack())){
                thisFields = StringUtils.join(yqfolderFields,",")+",";
            }else if ("x".equals(item.getFeedBack())){
                thisFields = StringUtils.join(yqItmeFields,",")+",";
            }else {
                thisFields = "*,";
            }
            Map<String, Object> archiveMap = yqDaBorrowMapper.selectArchiveByCategoryIdAndArchiveIdAndSubTableName(thisFields,archiveId,categoryId,subTableName);
            //补充借阅档案类型  电子or实体
            archiveMap.put("BORROW_TYPE",yqDaBorrow.getDaType());
            archiveMap.put("DA_TYPE",item.getFeedBack());
            item.setArchiveData(archiveMap);
        }
        return yqDaBorrow;
    }

    /**
     * 查询archiveBorrow列表
     *
     * @param yqDaBorrow archiveBorrow
     * @return archiveBorrow
     */
    @Override
    public List<YqDaBorrow> selectYqDaBorrowList(YqDaBorrow yqDaBorrow)
    {
        return yqDaBorrowMapper.selectYqDaBorrowList(yqDaBorrow);
    }
    @Override
    public List<YqDaBorrow> selectYqDaBorrowList1(YqDaBorrow yqDaBorrow)
    {
        return yqDaBorrowMapper.selectYqDaBorrowList1(yqDaBorrow);
    }
    /**
     * 新增archiveBorrow
     *
     * @param yqDaBorrow archiveBorrow
     * @return 结果
     */
    @Transactional
    @Override
    public int insertYqDaBorrow(YqDaBorrow yqDaBorrow)
    {
        yqDaBorrow.setCreateTime(DateUtils.getNowDate());
        int rows = yqDaBorrowMapper.insertYqDaBorrow(yqDaBorrow);
        insertYqdaborrowItem(yqDaBorrow);
        return rows;
    }

    /**
     * 修改archiveBorrow
     *
     * @param yqDaBorrow archiveBorrow
     * @return 结果
     */
    //@Transactional
    @Override
    public int updateYqDaBorrow(YqDaBorrow yqDaBorrow)
    {
        yqDaBorrow.setStatus(2);
        yqDaBorrowMapper.deleteYqdaborrowItemByBorrowId(yqDaBorrow.getBorrowId());
        List<YqdaborrowItem> yqdaborrowItemList = yqDaBorrow.getYqdaborrowItemList();
        for (YqdaborrowItem yqdaborrowItem : yqdaborrowItemList) {
            yqdaborrowItem.setStatus("2");
        }
        insertYqdaborrowItem(yqDaBorrow);
        YqDaBorrow yqDaBorrow1 = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(yqDaBorrow.getBorrowId());

        if ("F".equals(yqDaBorrow1.getDaType())&&"2".equals(yqDaBorrow1.getLiyongfangshi())){
            //update stjsfjc
            for (YqdaborrowItem yqdaborrowItem : yqdaborrowItemList) {
                String daId = yqdaborrowItem.getDaId();
                String subTableName = yqdaborrowItem.getSubTableName();
                Long categoryId = yqdaborrowItem.getCategoryId();
                Map<String, Object> category = yqDaBorrowMapper.selectCategory(SecurityUtils.getTenantCode().toUpperCase() + "_CATEGORY", categoryId);
                String fileTableName = String.valueOf(category.get("FILE_TABLE_NAME"));
                String folderTableName = String.valueOf(category.get("FOLDER_TABLE_NAME"));
                String itemTableName = String.valueOf(category.get("ITEM_TABLE_NAME"));

                String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
                if (subTableName.equals(fileTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",subTableName,"0",daId);
                }else if (subTableName.equals(folderTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",subTableName,"0",daId);
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"0","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID ='" +daId+"'");
                }else if (subTableName.equals(itemTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("ITEM_ID",tenantCode+"_YQITEM",subTableName,"0",daId);
                    yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",folderTableName,"0","SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"'");
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"0","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"')");
                }

                //消息通知预约人
                List<Map<String, Object>> maps = yqDaBorrowMapper.executeSqlFunction("select ID, USER_ID from " + SecurityUtils.getTenantCode()
                        + "_APPOINTMENT_FORM where STATUS = 0 and FIND_IN_SET( '" + daId + "', DA_IDS::text)>0 ");
                if (maps != null && maps.size() > 0) {
                    String userId =String.valueOf(maps.get(0).get("USER_ID"));
                    String id =maps.stream().map(m->String.valueOf(m.get("ID"))).collect(Collectors.joining("','"));
                    archiveReleaseService.addyqXxtzApi("您有" + maps.size() + "条预约的档案已经归还,请于次日12点之前发起借阅!", Long.valueOf(userId),  Long.valueOf(userId), SecurityUtils.getTenantCode());
                    yqDaBorrowMapper.executeSqlFunction("update " + SecurityUtils.getTenantCode()
                            + "_APPOINTMENT_FORM set borrow_time = '"+DateUtils.getTime()+"' where  id in ('"+id+"')");
                }
            }
        }
        return yqDaBorrowMapper.updateYqDaBorrow(yqDaBorrow);
    }

    /**
     * 修改archiveBorrow
     *
     * @param yqDaBorrow archiveBorrow
     * @return 结果
     */
    //@Transactional
    @Override
    public int updateYqDaBorrowStatus(YqDaBorrow yqDaBorrow)
    {
        List<YqdaborrowItem> yqdaborrowItemList = yqDaBorrow.getYqdaborrowItemList();
        YqDaBorrow yqDaBorrow1 = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(yqDaBorrow.getBorrowId());

        if ("F".equals(yqDaBorrow1.getDaType())&&"2".equals(yqDaBorrow1.getLiyongfangshi())){
            //update stjsfjc
            for (YqdaborrowItem yqdaborrowItem : yqdaborrowItemList) {
                String daId = yqdaborrowItem.getDaId();
                String subTableName = yqdaborrowItem.getSubTableName();
                Long categoryId = yqdaborrowItem.getCategoryId();
                Map<String, Object> category = yqDaBorrowMapper.selectCategory(SecurityUtils.getTenantCode().toUpperCase() + "_CATEGORY", categoryId);
                String fileTableName = String.valueOf(category.get("FILE_TABLE_NAME"));
                String folderTableName = String.valueOf(category.get("FOLDER_TABLE_NAME"));
                String itemTableName = String.valueOf(category.get("ITEM_TABLE_NAME"));

                String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
                if (subTableName.equals(fileTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",subTableName,"0",daId);
                }else if (subTableName.equals(folderTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",subTableName,"0",daId);
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"0","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID ='" +daId+"'");
                }else if (subTableName.equals(itemTableName)){
                    yqDaBorrowMapper.updateArchiveSFJCNew("ITEM_ID",tenantCode+"_YQITEM",subTableName,"0",daId);
                    yqDaBorrowMapper.updateArchiveSFJCNew("FOLDER_ID",tenantCode+"_YQFOLDER",folderTableName,"0","SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"'");
                    yqDaBorrowMapper.updateArchiveSFJCNew("DA_ID",tenantCode+"_YQDA",fileTableName,"0","SELECT DA_ID FROM "+tenantCode+"_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM "+tenantCode+"_ITEM_FOLDER WHERE ITEM_ID ='" +daId+"')");
                }
            }
        }
        return yqDaBorrowMapper.updateYqDaBorrow(yqDaBorrow);
    }

    /**
     * 批量删除archiveBorrow
     *
     * @param borrowIds 需要删除的archiveBorrow主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteYqDaBorrowByBorrowIds(Long[] borrowIds)
    {
        yqDaBorrowMapper.deleteYqdaborrowItemByBorrowIds(borrowIds);
        return yqDaBorrowMapper.deleteYqDaBorrowByBorrowIds(borrowIds);
    }

    /**
     * 删除archiveBorrow信息
     *
     * @param borrowId archiveBorrow主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteYqDaBorrowByBorrowId(Long borrowId)
    {
        yqDaBorrowMapper.deleteYqdaborrowItemByBorrowId(borrowId);
        return yqDaBorrowMapper.deleteYqDaBorrowByBorrowId(borrowId);
    }

    @Override
    public List<YqdaborrowItem> selectYqDaBorrowItemList(YqdaborrowItem yqdaborrowItem) {
        return yqDaBorrowMapper.selectYqDaBorrowItemList(yqdaborrowItem);
    }

    @Override
    public int endWorkFlowByInstanceId(YqDaBorrow yqDaBorrow) {
        YqDaBorrow selectBorrow = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(yqDaBorrow.getBorrowId());
        R<Boolean> result = remoteActivitiService.endWorkFlowInstance("取消借阅",selectBorrow.getProcessId());
        if (result.getData()){
            selectBorrow.getYqdaborrowItemList().forEach(item->{
                item.setStatus("-1");
            });
            selectBorrow.setStatus(-1);
            yqDaBorrowMapper.deleteYqdaborrowItemByBorrowId(selectBorrow.getBorrowId());
            insertYqdaborrowItem(selectBorrow);
            return yqDaBorrowMapper.updateYqDaBorrow(selectBorrow);
        }else {
            return 0;
        }
    }

    @Override
    public int updateArchiveBorrowDate(YqDaBorrow yqDaBorrow) {
        return yqDaBorrowMapper.updateYqDaBorrow(yqDaBorrow);
    }


    @Override
    public int updateYqDaBorrowMyd(YqDaBorrow yqDaBorrow) {
        return yqDaBorrowMapper.updateYqDaBorrowMyd(yqDaBorrow);
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveCategory(Long categoryId, String archiveId) {

        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String daType = null;
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
            daType = "F";
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
            daType = "V";
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
            daType = "X";
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        //FIXME 测试用字段
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
        fieldCommon.append("*,");


        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        sqlBulider.append("SELECT ").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveId).append(") AND IS_DEL = 0");
        return yqDaBorrowMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public int updateAllStatus(Long userId) {
        return yqDaBorrowMapper.updateAllStatus(userId);
    }

    @Override
    public List<Map<String, Object>> executeSqlFunction(String sql) {
        return yqDaBorrowMapper.executeSqlFunction(sql);
    }

    @Override
    public int borrowItemMinusOne(String itemId) {
        return yqDaBorrowMapper.borrowItemMinusOne(itemId);
    }

    @Override
    public int borrowItemMinusOnePrint(String itemId) {
        return yqDaBorrowMapper.borrowItemMinusOnePrint(itemId);
    }

    @Override
    public void cuihuan(Long id, String msg) {
        YqDaBorrow borrow = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(id);
        yqXxtzService.addyqXxtzApi(msg,SecurityUtils.getUserId(),borrow.getBorrowUser(),SecurityUtils.getTenantCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String receive(Long borrowId) {
        YqDaBorrow yqDaBorrow = yqDaBorrowMapper.selectYqDaBorrowByBorrowId(borrowId);
        if(!"F".equals(yqDaBorrow.getDaType())){
            return "非实体借阅,无需领取!";
        }

        if(null!=yqDaBorrow.getIsReceive()&&1==yqDaBorrow.getIsReceive()){
            return "已经领取,请勿重复操作!";
        }
        YqDaBorrow updateyqdaborrow=new YqDaBorrow();
        updateyqdaborrow.setBorrowId(borrowId);
        updateyqdaborrow.setIsReceive(1);
        updateyqdaborrow.setReceiveTime(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        updateyqdaborrow.setStartTime(DateUtils.getNowDate());
        updateyqdaborrow.setEndTime(DateUtils.addDate(DateUtils.getNowDate(), yqDaBorrow.getBorrowDays()));
        if("1".equals(yqDaBorrow.getLiyongfangshi())){//复印件
            updateyqdaborrow.setStatus(2);
            //处理item
            yqDaBorrowMapper.updateborrowitem(borrowId);

        }else{

        }
        yqDaBorrowMapper.updateYqDaBorrow(updateyqdaborrow);
        return "成功";
    }

    @Override
    public YqDaBorrow getdetail(Long borrowId) {
        YqDaBorrow yqDaBorrow=new YqDaBorrow();
        yqDaBorrow.setBorrowId(borrowId);
        YqDaBorrow yqDaBorrow1 = yqDaBorrowMapper.selectYqDaBorrowList(yqDaBorrow).get(0);
        return yqDaBorrow1;
    }

    @Override
    public YqdaborrowItem selectYqDaBorrowItemById(String itemId) {
        return yqDaBorrowMapper.selectYqDaBorrowItemById(itemId);
    }

    /**
     * 新增archiveBorrowItem信息
     *
     * @param yqDaBorrow archiveBorrow对象
     */
    public void insertYqdaborrowItem(YqDaBorrow yqDaBorrow)
    {
        List<YqdaborrowItem> yqdaborrowItemList = yqDaBorrow.getYqdaborrowItemList();
        Long borrowId = yqDaBorrow.getBorrowId();
        if (StringUtils.isNotNull(yqdaborrowItemList))
        {
            List<YqdaborrowItem> list = new ArrayList<YqdaborrowItem>();
            for (YqdaborrowItem yqdaborrowItem : yqdaborrowItemList)
            {
                yqdaborrowItem.setBorrowId(borrowId);
                list.add(yqdaborrowItem);
            }
            if (list.size() > 0)
            {
                yqDaBorrowMapper.batchYqdaborrowItem(list);
            }
        }
    }
}
